package com.jet.chat.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import com.jet.chat.exception.ChatExceptionClientReaderNotAvailable;
import com.jet.chat.exception.ChatExceptionClientWriterNotAvailable;
import com.jet.chat.exception.ChatExceptionServerHostNotAvailable;


public class ChatClient {
	private String serverHost;
	private int serverPort;
	private Socket socket;
	private BufferedReader reader;
	private PrintWriter writer;
	
	public ChatClient(String serverHost, int serverPort) throws ChatExceptionServerHostNotAvailable, ChatExceptionClientReaderNotAvailable, ChatExceptionClientWriterNotAvailable {
		this.serverHost = serverHost;
		this.serverPort = serverPort;
		
		try {
			this.socket = new Socket(serverHost, serverPort);
		} catch (UnknownHostException e) {
			throw new ChatExceptionServerHostNotAvailable("host not found");
			//e.printStackTrace();
		} catch (IOException e) {
			throw new ChatExceptionServerHostNotAvailable("ololo netnet net");
			//e.printStackTrace();
		}

		try {
			this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {
			throw new ChatExceptionClientReaderNotAvailable("ошибка создания потока чтения клиента");
			//e.printStackTrace();
		}
		
		try {
			this.writer = new PrintWriter(socket.getOutputStream());
		} catch (IOException e) {
			throw new ChatExceptionClientWriterNotAvailable("ошибка создания потока вывода клиента");
			//e.printStackTrace();
		}
	}
	
	public void execute() {
		new Thread(new ChatClientServerReader(reader)).start();
		new Thread(new ChatClientConsoleReader(writer)).start();
	}

	public static void main(String[] arg) {
		ChatClient chatClient;
		try {
			chatClient = new ChatClient("localhost", 30030);
			chatClient.execute();
		} catch (ChatExceptionServerHostNotAvailable e) {
			e.printStackTrace();
		} catch (ChatExceptionClientReaderNotAvailable e) {
			e.printStackTrace();
		} catch (ChatExceptionClientWriterNotAvailable e) {
			e.printStackTrace();
		}
	}
}
